﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Timers;
using System.Windows.Forms;

namespace TestModBus
{
    public class SerialPortUtil
    {
        //private static SerialPortUtil instance;
        //private static object _lock = new object();
        //public static SerialPortUtil GetInstance()
        //{
        //    if (instance == null)
        //    {
        //        lock (_lock)
        //        {
        //            if (instance == null)
        //            {
        //                instance = new SerialPortUtil();
        //            }
        //        }
        //    }
        //    return instance;
        //}

        public SerialPort _serialPort = null;
        public delegate void SerialPortNomalEventArgs(byte[] bits);
        public delegate void SerialPortErrorEventArgs(string str);
        public delegate void ComTimeCheck(int e);
        //定义接收数据事件
        public event SerialPortNomalEventArgs CallDataReceived;
        //定义接收错误事件
        public event SerialPortErrorEventArgs CallReceivedError;
        //串口实时监测回调,如果连接断开，则操作重连接
        public event ComTimeCheck CallComTimeCheckEvent;
        //接收事件是否有效 false表示有效
        private bool ReceiveEventFlag = false;

        ///检查串口状态
        Thread thCheckSerialState;
        private bool CloseChechSerialState;
        /// <summary>
        /// 超时未接收到数据
        /// </summary>
        System.Timers.Timer TimeoutHand = null;
        ConcurrentQueue<int> queue = new ConcurrentQueue<int>();
        private int _TimeOut = 2000;
        /// <summary>
        /// 超时时间
        /// </summary>
        public int TimeOut
        {
            get { return _TimeOut; }
            set { _TimeOut = value; }
        }

        #region 属性

        // 获取串口名
        private string protName;
        public string PortName
        {
            get { return _serialPort.PortName; }
            set
            {
                _serialPort.PortName = value;
                protName = value;
            }
        }

        // 获取比特率
        private int baudRate;
        public int BaudRate
        {
            get { return _serialPort.BaudRate; }
            set
            {
                _serialPort.BaudRate = value;
                baudRate = value;
            }

        }

        #endregion

        public bool IsConect { get; set; }

        public SerialPortUtil()
        {
            //TimeoutHand = new System.Timers.Timer(TimeOut);
            //TimeoutHand.Elapsed += new System.Timers.ElapsedEventHandler(TimerCallBack);
            //TimeoutHand.AutoReset = false;
            //TimeoutHand.Enabled = false;
        }

        private void TimerCallBack(object sender, ElapsedEventArgs e)
        {
            if (queue.Count > 0)
            {
                int iss = 0;
                while (!queue.TryDequeue(out iss))
                {
                    break;
                }
            }
            else //超时了,重发指令
            {
                //超时接收
                CallComTimeCheckEvent(2);
            }
        }

        int TimeReconnet = 0;

        /// <summary>
        /// 开启实时监控 ==重连10次断开
        /// </summary>
        private void TurnTimeCheckConnState()
        {
            thCheckSerialState = new Thread(new ThreadStart(delegate
            {
                while (true)
                {
                    if (IsConect)
                    {
                        if (CloseChechSerialState)
                        {
                            CloseChechSerialState = false;
                            break;
                        }
                        if (_serialPort != null)
                        {
                            if (!_serialPort.IsOpen)
                            {
                                if (CallComTimeCheckEvent != null)
                                {
                                    TimeReconnet++;
                                    if (TimeReconnet == 10)
                                    {
                                        TimeReconnet = 0;
                                        break;
                                    }
                                    //连接断开,重新连接
                                    //CallComTimeCheckEvent(1);
                                    OpenPort();
                                }
                            }
                        }
                    }
                    Thread.CurrentThread.Join(500);//设定时间500ms
                }
            }));
            thCheckSerialState.Start();//启动线程
        }

        /// <summary>
        /// 初始化串口参数
        /// </summary>
        /// <param name="comPortName"></param>
        /// <param name="baudRate"></param>
        /// <param name="parity"></param>
        /// <param name="dataBits"></param>
        /// <param name="stopBits"></param>
        public void Inin(string comPortName, SerialPortBaudRates baudRate, Parity parity, SerialPortDatabits dataBits, StopBits stopBits)
        {
            _serialPort = new SerialPort(comPortName, (int)baudRate, parity, (int)dataBits, stopBits);
            // 是否启用串口发送 启用串口发送
            _serialPort.RtsEnable = true;  
            _serialPort.ReadTimeout = 5000;
            _serialPort.WriteTimeout = 5000;
            //设置串口协议
            //_serialPort.Handshake = Handshake.None;
            //_serialPort.NewLine = "/r/n";
            //设置触发DataReceived事件的字节数为1
            //_serialPort.ReceivedBytesThreshold = 1;
            //接收到一个字节时，也会触发DataReceived事件
            _serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);
            //接收数据出错,触发事件
            _serialPort.ErrorReceived += new SerialErrorReceivedEventHandler(_serialPort_ErrorReceived);
            //启动串口实时监测
            //TurnTimeCheckConnState();
        }

        /// <summary>
        /// 设置串口参数
        /// </summary>
        /// <param name="comPortName">需要操作的COM口名称</param>
        /// <param name="baudRate">COM的速度</param>
        /// <param name="dataBits">数据长度</param>
        /// <param name="stopBits">停止位</param>
        public void SetSerialPort(string comPortName)
        {
            if (_serialPort.IsOpen)
                _serialPort.Close();
            _serialPort.PortName = comPortName;
            OpenPort();
        }

        #region 打开串口资源

        /// <summary>
        /// 打开串口资源
        /// <returns>返回bool类型</returns>
        /// </summary>
        public bool OpenPort()
        {
            bool ok = false;
            //如果串口是打开的，先关闭
            if (_serialPort.IsOpen)
                _serialPort.Close();
            try
            {
                do
                {
                    //打开串口
                    _serialPort.Open();
                    ok = true;
                    IsConect = true;
                }
                while (!_serialPort.IsOpen);
            }
            catch (Exception Ex)
            {
                CallReceivedError?.Invoke(Ex.Message);
            }
            return ok;
        }
        #endregion

        #region 关闭串口

        /// <summary>
        /// 关闭串口资源,操作完成后,一定要关闭串口
        /// </summary>
        public void ClosePort()
        {
            if (_serialPort != null)
            {
                //如果串口处于打开状态,则关闭
                if (_serialPort.IsOpen)
                    _serialPort.Close();
                IsConect = false;

            }
        }

        /// <summary>
        /// 关闭清除全部
        /// </summary>
        public void CloseClearAll()
        {
            if (_serialPort != null)
            {
                //如果串口处于打开状态,则关闭
                if (_serialPort.IsOpen)
                    _serialPort.Close();
                if (thCheckSerialState != null)
                {
                    CloseChechSerialState = true;
                    Thread.CurrentThread.Join(400);
                    thCheckSerialState.Abort();
                }

                _serialPort = null;
                IsConect = false;
            }
        }
        #endregion

        #region 接收串口数据事件

        /// <summary>
        /// 接收串口数据事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //记录是否接收到信号
            //queue.Enqueue(1);
            //禁止接收事件时直接退出
            //if (ReceiveEventFlag)
            //{
            //    return;
            //}
            try
            {
                Thread.Sleep(200);
                byte[] _data = new byte[_serialPort.BytesToRead];
                _serialPort.Read(_data, 0, _data.Length);
                SerialPortUtil.SerialPortNomalEventArgs expr_9A = this.CallDataReceived;
                if (expr_9A != null)
                {
                    expr_9A(_data);
                }
                //_serialPort.DiscardInBuffer();  //清空接收缓冲区  
                //_serialPort.Close();
            }
            catch (Exception ex)
            {
                CallReceivedError?.Invoke("串口报错:" + ex.Message + "\r\n" + ex.StackTrace.ToString());
            }
        }

        #endregion

        #region 接收数据出错事件

        /// <summary>
        /// 接收数据出错事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _serialPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
        {
            if (CallReceivedError != null)
            {
                string str = string.Empty;
                if (e.EventType == SerialError.Frame)
                {
                    str = "成帧差错-->" + e.ToString();
                }
                else if (e.EventType == SerialError.Overrun)
                {
                    str = "字符缓冲区溢出-->" + e.ToString();
                }
                else if (e.EventType == SerialError.RXOver)
                {
                    str = "输入缓冲区溢出-->" + e.ToString();
                }
                else if (e.EventType == SerialError.RXParity)
                {
                    str = "pada硬件校验错误-->" + e.ToString();
                }
                else if (e.EventType == SerialError.TXFull)
                {
                    str = "传输数据，namun输出缓冲sedang penuh" + e.ToString();
                }
                CallReceivedError(str);
            }
        }
        #endregion

        #region 发送数据string类型
        public void SendData(string data)
        {
            if (_serialPort == null)
                return;
            //发送数据
            //禁止接收事件时直接退出
            if (ReceiveEventFlag)
            {
                return;
            }
            if (_serialPort.IsOpen)
            {
                _serialPort.Write(data);
                //TimeoutHand.Enabled = true;
            }
        }

        #endregion

        #region 发送数据byte类型
        /// <summary>
        /// 数据发送
        /// </summary>
        /// <param name="data">要发送的数据字节</param>
        public void SendData(byte[] data, int offset, int count)
        {
            //禁止接收事件时直接退出
            if (ReceiveEventFlag)
            {
                return;
            }
            try
            {
                if (!_serialPort.IsOpen)
                    _serialPort.Open();
                _serialPort.DiscardInBuffer();//清空接收缓冲区
                _serialPort.Write(data, offset, count);
            }
            catch (Exception ex)
            {
                CallReceivedError?.Invoke(ex.Message);
            }
        }
        #endregion

        #region 发送命令
        /// <summary>
        /// 发送命令
        /// </summary>
        /// <param name="SendData">发送数据</param>
        /// <param name="ReceiveData">接收数据</param>
        /// <param name="Overtime">超时时间</param>
        /// <returns></returns>
        public int SendCommand(byte[] SendData, ref byte[] ReceiveData, int Overtime)
        {
            if (_serialPort.IsOpen)
            {
                try
                {
                    ReceiveEventFlag = true;        //关闭接收事件
                    _serialPort.DiscardInBuffer();  //清空接收缓冲区                
                    _serialPort.Write(SendData, 0, SendData.Length);
                    int num = 0, ret = 0;
                    System.Threading.Thread.Sleep(10);
                    //ReceiveEventFlag = false;      //打开事件
                    while (num++ < Overtime)
                    {
                        if (_serialPort.BytesToRead >= ReceiveData.Length)
                            break;
                        System.Threading.Thread.Sleep(10);
                    }
                    if (_serialPort.BytesToRead >= ReceiveData.Length)
                    {
                        ret = _serialPort.Read(ReceiveData, 0, ReceiveData.Length);
                    }
                    else
                    {
                        ret = _serialPort.Read(ReceiveData, 0, _serialPort.BytesToRead);
                    }
                    ReceiveEventFlag = false;      //打开事件
                    return ret;
                }
                catch (Exception ex)
                {
                    ReceiveEventFlag = false;
                    CallReceivedError?.Invoke(ex.Message);
                }
            }
            return -1;
        }
        #endregion

        #region 获取当前全部串口资源
        /// <summary>
        /// 获得当前电脑上的所有串口资源
        /// </summary>
        /// <returns></returns>
        public string[] GetSerials()
        {
            return SerialPort.GetPortNames();
        }

        #endregion

        #region 字节型转换16
        /// <summary>
        /// 把字节型转换成十六进制字符串
        /// </summary>
        /// <param name="InBytes"></param>
        /// <returns></returns>
        public static string ByteToString(byte[] InBytes)
        {
            string StringOut = "";
            foreach (byte InByte in InBytes)
            {
                StringOut = StringOut + String.Format("{0:X2} ", InByte);
            }
            return StringOut;
        }
        #endregion

        #region 十六进制字符串转字节型
        /// <summary>
        /// 把十六进制字符串转换成字节型(方法1)
        /// </summary>
        /// <param name="InString"></param>
        /// <returns></returns>
        public static byte[] StringToByte(string InString)
        {
            string[] ByteStrings;
            ByteStrings = InString.Split(" ".ToCharArray());
            byte[] ByteOut;
            ByteOut = new byte[ByteStrings.Length];
            for (int i = 0; i <= ByteStrings.Length - 1; i++)
            {
                //ByteOut[i] = System.Text.Encoding.ASCII.GetBytes(ByteStrings[i]);
                ByteOut[i] = Byte.Parse(ByteStrings[i], System.Globalization.NumberStyles.HexNumber);
                //ByteOut[i] =Convert.ToByte("0x" + ByteStrings[i]);
            }
            return ByteOut;
        }

        #endregion

        #region 十六进制字符串转字节型
        /// <summary>
        /// 字符串转16进制字节数组(方法2)
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public byte[] StrToToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        #endregion

        #region 字节型转十六进制字符串
        /// <summary>
        /// 字节数组转16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ByteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }
        #endregion
    }
}
